package com.lucas.rpc.framework.transport.socket;

import com.lucas.rpc.framework.entity.RpcRequest;
import com.lucas.rpc.framework.entity.RpcResponse;
import com.lucas.rpc.framework.entity.URL;
import com.lucas.rpc.framework.loadbalance.RandomLoadBalance;
import com.lucas.rpc.framework.server.register.FakeRemoteRegister;
import com.lucas.rpc.framework.transport.RpcTransport;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

/**
 * @author: LiuCheng
 * @description:
 * @date: 2023-12-04 14:55
 **/
public class SocketRpcClient implements RpcTransport {
    @Override
    public RpcResponse sendRpcRequest(RpcRequest rpcRequest) {
        try{
            //从注册中心根据接口名拿到server的urls
            List<URL> urls = FakeRemoteRegister.getURLs(rpcRequest.getInterfaceName());
            //负载均衡
            URL url = RandomLoadBalance.selectURL(urls);

            //发送请求
            Socket socket = new Socket(url.getHostname(),url.getPort());

            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

            oos.writeObject(rpcRequest);
            oos.flush();

            //接收响应
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            RpcResponse rpcResponse = (RpcResponse) ois.readObject();
            ois.close();
            oos.close();
            return rpcResponse;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
